package com.showworkflow.service;

import org.springframework.stereotype.Service;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class word2html_pandoc {

    private String workingPandocCommand = null; // 保存成功的Pandoc命令

    // 检查Pandoc是否安装
    public boolean checkPandocInstallation() {
        try {
            // Windows环境下尝试多种方式查找pandoc
            String[] commands = {
                "C:\\Users\\admin\\AppData\\Local\\Pandoc\\pandoc.exe",
                "C:\\Users\\" + System.getProperty("user.name") + "\\AppData\\Local\\Pandoc\\pandoc.exe",
                "pandoc",
                "pandoc.exe",
                "C:\\Program Files\\Pandoc\\pandoc.exe",
                "C:\\Program Files (x86)\\Pandoc\\pandoc.exe"
            };

            for (String command : commands) {
                try {
                    Process process = new ProcessBuilder(command, "--version")
                            .redirectErrorStream(true)
                            .start();

                    // 等待进程完成
                    int exitCode = process.waitFor();
                    if (exitCode == 0) {
                        System.out.println("找到Pandoc: " + command);
                        workingPandocCommand = command; // 保存工作的命令
                        return true;
                    }
                } catch (IOException | InterruptedException e) {
                    // 继续尝试下一个路径
                    continue;
                }
            }

            // 如果所有路径都失败，尝试使用cmd /c pandoc
            try {
                Process process = new ProcessBuilder("cmd", "/c", "pandoc", "--version")
                        .redirectErrorStream(true)
                        .start();
                int exitCode = process.waitFor();
                if (exitCode == 0) {
                    System.out.println("通过cmd找到Pandoc");
                    workingPandocCommand = "cmd /c pandoc"; // 保存工作的命令组合
                    return true;
                }
            } catch (IOException | InterruptedException e) {
                // 最后的尝试也失败了
            }

            return false;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 使用Pandoc将Word文档转换为HTML
     *
     * @param inputFilePath 输入Word文件路径(.docx或.doc)
     * @param outputFilePath 输出HTML文件路径
     * @param mediaDir 媒体文件(图片等)提取目录，null则不单独提取
     * @param standalone 是否生成完整的HTML文档(包含头部信息)
     * @param mathml 是否转换数学公式为MathML
     * @param highlightStyle 代码高亮风格(如github, pygments等)
     * @return 转换是否成功
     * @throws IOException 当文件操作或进程执行出错时抛出
     * @throws InterruptedException 当进程被中断时抛出
     */
    public boolean convertWordToHtml(String inputFilePath, String outputFilePath,
                                     String mediaDir, boolean standalone,
                                     boolean mathml, String highlightStyle)
            throws IOException, InterruptedException {

        // 验证输入文件是否存在
        File inputFile = new File(inputFilePath);
        if (!inputFile.exists() || !inputFile.isFile()) {
            throw new FileNotFoundException("输入文件不存在: " + inputFilePath);
        }

        // 创建输出目录(如果需要)
        File outputFile = new File(outputFilePath);
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }

        // 构建Pandoc命令
        List<String> command = new ArrayList<>();

        // 检查操作系统类型，Windows下使用cmd /c执行
        String os = System.getProperty("os.name").toLowerCase();

        // 优先使用检测到的工作命令
        if (workingPandocCommand != null) {
            if (workingPandocCommand.contains("cmd /c pandoc")) {
                command.add("cmd");
                command.add("/c");
                command.add("pandoc");
            } else {
                command.add(workingPandocCommand);
            }
        } else if (os.contains("windows")) {
            command.add("cmd");
            command.add("/c");
            command.add("pandoc");
        } else {
            command.add("pandoc");
        }

        command.add(inputFilePath);
        command.add("-o");
        command.add(outputFilePath);

        // 添加额外参数
        if (standalone) {
            command.add("--standalone");
        }

        if (mathml) {
            command.add("--mathml");
        }

        if (highlightStyle != null && !highlightStyle.isEmpty()) {
            // 跳过高亮样式以避免兼容性问题
            // 对于Word文档转HTML，通常不需要代码高亮
            System.out.println("跳过代码高亮样式设置，避免兼容性问题");
        }

        if (mediaDir != null && !mediaDir.isEmpty()) {
            Path mediaPath = Paths.get(mediaDir);
            Files.createDirectories(mediaPath); // 确保媒体目录存在
            command.add("--extract-media");
            command.add(mediaDir);
        }

        // 执行命令
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.redirectErrorStream(true); // 合并错误流到输出流

        // 为Windows环境设置编码
        if (os.contains("windows")) {
            processBuilder.environment().put("JAVA_TOOL_OPTIONS", "-Dfile.encoding=UTF-8");
        }

        Process process = processBuilder.start();

        // 读取输出
        StringBuilder output = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {

            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        }

        // 等待进程完成
        int exitCode = process.waitFor();

        // 检查输出文件是否生成
        if (exitCode == 0 && !new File(outputFilePath).exists()) {
            throw new IOException("转换成功但未生成输出文件: " + outputFilePath);
        }

        // 输出Pandoc的日志信息
        System.out.println("Pandoc命令: " + String.join(" ", command));
        System.out.println("Pandoc退出码: " + exitCode);
        System.out.println("Pandoc转换日志:\n" + output.toString());

        if (exitCode != 0) {
            System.err.println("Pandoc转换失败，退出码: " + exitCode);
            System.err.println("错误输出: " + output.toString());
        }

        return exitCode == 0;
    }

    // 示例用法
    public static void main(String[] args) {
        word2html_pandoc converter = new word2html_pandoc();

        // 检查Pandoc是否安装
        if (!converter.checkPandocInstallation()) {
            System.err.println("未检测到Pandoc，请先安装Pandoc: https://pandoc.org/installing.html");
            return;
        }

        try {
            // 转换参数设置
            String inputPath = "input.docx";
            String outputPath = "output.html";
            String mediaDir = "media"; // 提取图片等媒体文件到media目录

            boolean success = converter.convertWordToHtml(
                    inputPath,
                    outputPath,
                    mediaDir,
                    true,  // 生成完整HTML
                    true,  // 转换数学公式
                    "github"  // 使用github风格的代码高亮
            );

            if (success) {
                System.out.println("转换成功! 输出文件: " + outputPath);
                if (new File(mediaDir).exists()) {
                    System.out.println("媒体文件目录: " + mediaDir);
                }
            } else {
                System.err.println("转换失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
